package cn.zxh.csdn_maven.atomy.auth.GetSourceList;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.client.HttpClient;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

@SuppressWarnings("unused")
public abstract class AbstractSource implements SourceService{

	private static final String UNCHECKED = "unchecked";
	private Logger logger=Logger.getLogger(AbstractSource.class);
	private Map<String, Object> result=new HashMap<String, Object>();
	
	/**自由的抽象方法*/
	public abstract Map<String, Object> execute(HttpClient client,Map<String, Object> params) throws Exception;
	public abstract String getBaseUrl();
	
	public Map<String, Object> run(HttpClient client, Map<String, Object> params) throws Exception {
		/**添加子类抓取的信息*/
		mixTogether(result, execute(client, params));
		if(result.size()==0){
			throw new Exception("获取"+getBaseUrl()+"系列地址资源失败");
		}
		Integer times = Integer.parseInt(result.get("times").toString());
		/**从第二页开始，第一页已经获取到了*/
		for (int i = 1; i < times; i++) {
			/**装入实际页数*/
			params.put("times", i+1);
			mixTogether(result, execute(client, params));
		}
		return result;
	}

	@SuppressWarnings(UNCHECKED)
	public void mixTogether(Map<String,Object> sourceMap,Map<String,Object> targetMap){
		for(Entry<?, ?> entry : targetMap.entrySet()){
			if(sourceMap.containsKey(entry.getKey())){
				/**原map(sorceMap)已经存在了entry.getkey(),进行融合*/
				Object sourceValue = sourceMap.get(entry.getKey());
				if(sourceValue instanceof List<?>){
					List<Object> sourceList = ((List<Object>) sourceValue);
					sourceList.addAll((Collection<? extends Object>) entry.getValue());
					sourceMap.put(entry.getKey().toString(),sourceList);
				}else if (sourceValue instanceof JSONArray) {
					JSONArray newJsonArray = (JSONArray) sourceValue;
					/**获取待加入集合*/
					JSONArray oldJsonArray = (JSONArray) entry.getValue();
					for (Object object : oldJsonArray) {
						JSONObject json = (JSONObject) object;
						newJsonArray.put(json);
					}
				}
			}else {
				sourceMap.put(entry.getKey().toString(),entry.getValue());
			}
		}
	}
}
